<template>
	<view>
		<nav-custom bgColor="bg-gradual-pink" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">消息列表</block>
		</nav-custom>
		<view class="content" @touchstart="hideEmoji">
			<scroll-view class="msg-list" scroll-y="true" :scroll-with-animation="scrollAnimation" :scroll-top="scrollTop"
			 :scroll-into-view="scrollToView" :style="[{top: isMPheight + 'px'}]">
				<view class="row" v-for="(row,index) in msgList" :key="index" :id="'msg'+row.id">
					<!-- 自己发出的消息 -->
					<view class="my" v-if="row.uid==myuid">
						<view class="left">
							<view v-if="row.type=='text'" class="bubble">
								<rich-text :nodes="row.msg.content"></rich-text>
							</view>
							<view v-if="row.type=='img'" class="bubble img" @tap="showPic(row)">
								<image :src="row.msg.url" :style="{'width': row.msg.w+'px','height': row.msg.h+'px'}"></image>
							</view>
						</view>
						<view class="right">
							<image :src="row.face"></image>
						</view>
					</view>
					<!-- 别人发出的消息 -->
					<view class="other" v-if="row.uid!=myuid">
						<view class="left">
							<image :src="row.face"></image>
						</view>
						<view class="right">
							<view class="username">
								<view class="name">{{row.username}}</view>
								<view class="time">{{row.time}}</view>
							</view>
							<view v-if="row.type=='text'" class="bubble">
								<rich-text :nodes="row.msg.content"></rich-text>
							</view>
							<view v-if="row.type=='img'" class="bubble img" @tap="showPic(row)">
								<image :src="row.msg.url" :style="{'width': row.msg.w+'px','height': row.msg.h+'px'}"></image>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<!-- 底部输入栏 -->
		<view class="input-box" :class="showEmji" @touchmove.stop.prevent="discard">
			<view class="more" @tap="chooseImage">
				<view class="iconfont icon-tupian"></view>
			</view>
			<view class="textbox">
				<view class="voice-mode" :class="[isVoice?'':'hidden',recording?'recording':'']" @touchstart="voiceBegin"
				 @touchmove.stop.prevent="voiceIng" @touchend="voiceEnd" @touchcancel="voiceCancel">{{voiceTis}}</view>
				<view class="text-mode" :class="isVoice?'hidden':''">
					<view class="box">
						<textarea auto-height="true" v-model="textMsg" />
						</view>
				</view>
			</view>
			<view class="send" :class="isVoice?'hidden':''" @tap="sendText">
				<view class="btn">
					发送
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	// 初始化一个 WebSocket 对象
	// var ws = new WebSocket("ws://121.40.165.18:8800");
	var socketOpen = false;
	export default {
		data() {
			return {
				isMPheight: 0,
				//房间title
				titleText: '',
				//收到的消息
				receivedMessage: '',
				//文字消息
				textMsg:'',
				//消息列表
				scrollAnimation:false,
				scrollTop:0,
				scrollToView:'',
				msgList:[],
				msgImgList:[],
				myuid:0,
				//录音相关参数
				// #ifndef H5
				//H5不能录音
				RECORDER:uni.getRecorderManager(),
				// #endif
				isVoice:false,
				voiceTis:'按住 说话',
				recordTis:"手指上滑 取消发送",
				recording:false,
				willStop:false,
				initPoint:{identifier:0,Y:0},
				recordTimer:null,
				recordLength:0,
				//播放语音相关参数
				AUDIO:uni.createInnerAudioContext(),
				playMsgid:null,
				VoiceTimer:null,
				//表情定义
				showEmji:'',
				emojiList:[],
				
			};
		},
		onLoad(option) {
			// uni.setNavigationBarTitle({
			// 	title: option.name
			// });
			this.isMPheight = this.CustomBar
			this.titleText = option.name
			this.getMsgList();
			//语音自然播放结束
			this.AUDIO.onEnded((res)=>{
				this.playMsgid=null;
			});
			// uni.clearStorage()
			// #ifndef H5
				//录音开始事件
				this.RECORDER.onStart((e)=>{
					this.recordBegin(e);
				})
				//录音结束事件
				this.RECORDER.onStop((e)=>{
					this.recordEnd(e);
				})
			// #endif
			// this.initWebSocket();	
		},
		watch: {
			receivedMessage(newName, oldName){
				let nowDate = new Date();
				let lastid = this.msgList[this.msgList.length-1].id;
				lastid++;
				if(newName.includes("url") && newName.includes('w') && newName.includes('h')){
					let msg = {id:lastid,uid:1,username:"售后客服008",face:"/static/img/face/face_2.jpg",time:nowDate.getHours()+":"+nowDate.getMinutes(),type:'img',msg: JSON.parse(newName)};
					this.screenMsg(msg);
				}else{
					let msg = {id:lastid,uid:1,username:"售后客服008",face:"/static/img/face/face_2.jpg",time:nowDate.getHours()+":"+nowDate.getMinutes(),type:'text',msg:{content:this.replaceEmoji(newName)}};
					this.screenMsg(msg);
				}
			}
		},
		onUnload() {
			uni.closeSocket();
		},
		methods:{
			initWebSocket(){ //初始化weosocket
				uni.connectSocket({
				  // url: 'ws://121.40.165.18:8800'
				  url: 'ws://123.207.167.163:9010/ajaxchattest'
				});
				uni.onSocketOpen((res) => {
				  console.log('连接成功')
				  socketOpen = true;
				});
				uni.onSocketMessage((res) => {
				  this.receivedMessage = res.data
				  console.log(res.data);
				});
				uni.onSocketError((res) => {
				  console.log('WebSocket连接打开失败，请检查！');
				});
				uni.onSocketClose((res) => {
				  console.log('WebSocket 已关闭！');
				});
			},
			getMsgList(){
				// 消息列表
				let list;
				// if(uni.getStorageSync('chatRecord')){
				// 	list = uni.getStorageSync('chatRecord')
				// }else{
					list = [
						{id:1,uid:1,username:"售后客服008",face:"https://img.zcool.cn/community/01a3865ab91314a8012062e3c38ff6.png",time:"12:57",type:"text",msg:{content:"您好！欢迎光临本店，请问有什么要帮助的吗？"}},
						{id:2,uid:0,username:"售后客服008",face:"https://img.zcool.cn/community/01a3865ab91314a8012062e3c38ff6.png",time:"12:57",type:"text",msg:{content:"你好！我想要租婚车：\r\n 婚期：2019年12月260日\r\n头车：奔驰\r\n跟车：奔驰\r\n预算：4000~6000\r\n请问有合适的套餐推荐吗"}}
					]
				// }
				let data = {
					msgType: 1
				}
				this.$api.MsgPull(data).then(res => {
					console.log(res)
				});
				// 获取消息中的图片,并处理显示尺寸
				for(let i=0;i<list.length;i++){
					if(list[i].type=='img'){
						list[i] = this.setPicSize(list[i]);
						// console.log("list[i]: " + JSON.stringify(list[i]));
						this.msgImgList.push(list[i].msg.url);
					}
				}
				uni.clearStorageSync()
				this.msgList = list;
				// 滚动到底部
				this.$nextTick(function() {
					this.scrollTop = 9999;
					this.scrollAnimation = true;
				});
			},
			//处理图片尺寸，如果不处理宽高，新进入页面加载图片时候会闪
			setPicSize(row){
				let maxW = uni.upx2px(350);
				let maxH = uni.upx2px(350);
				if(row.msg.w>maxW||row.msg.h>maxH){
					let scale = row.msg.w/row.msg.h;
					if(row.msg.w>row.msg.h){
						row.msg.w = maxW;
						row.msg.h = row.msg.w/scale
					}else{
						row.msg.h = maxH;
						row.msg.w = row.msg.h*scale;
					}
				}
				return row;
			},
			// 接受消息(筛选处理)
			screenMsg(msg){
				//从长连接处转发给这个方法，进行筛选处理
				if(msg.uid!=this.myuid){
					uni.vibrateLong();
				}
				switch (msg.type){
					case 'text':
						this.addTextMsg(msg);
						break;
					case 'voice':
						this.addVoiceMsg(msg);
						break;
					case 'img':
						this.addImgMsg(msg);
						break;
				}
				uni.setStorageSync('chatRecord',this.msgList)
				this.$nextTick(function() {
					this.scrollToView = 'msg'+msg.id
				});
			},
			// 选择表情
			chooseEmoji(){
				this.showEmji = this.showEmji=='showEmoji'?'hideEmoji':'showEmoji';
			},
			// 隐藏表情
			hideEmoji(){
				this.showEmji = this.showEmji=='showEmoji'?'hideEmoji':'';
			},
			//添加表情
			addEmoji(em){
				this.textMsg+=em.alt;
			},
			// 发送文字消息
			sendText(){

				if(!this.textMsg){
					return;
				}
				let data = {
					msgContent: this.textMsg,
					sendMethod: 1  //默认1文本、2图文、3链接
				}
				this.$api.MsgSend(data).then(res => {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
					if(res.code == 0){
						let msg = {
							content: '<div style="display: flex;align-items: center;">'+this.textMsg+'</div>',
						};
						this.sendMsg(msg,'text');
						this.textMsg = '';
					}
				});	
			},
			// 选择图片发送
			chooseImage(){
				uni.chooseImage({
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: (res)=>{
						for(let i=0;i<res.tempFilePaths.length;i++){
							uni.getImageInfo({
								src: res.tempFilePaths[i],
								success: (image)=>{
									// const tempFilePaths = chooseImageRes.tempFilePaths;
									// uni.uploadFile({
									// 	url: 'https://www.example.com/upload', //仅为示例，非真实的接口地址
									// 	filePath: tempFilePaths[0],
									// 	name: 'file',
									// 	formData: {
									// 		'user': 'test'
									// 	},
									// 	success: (uploadFileRes) => {
									// 		console.log(uploadFileRes.data);
									// 	}
									// });
									let msg = {url:res.tempFilePaths[i],w:image.width,h:image.height};
									let data = {
										msgContent: JSON.stringify(msg),
										sendMethod: 2  //默认1文本、2图文、3链接
									}
									this.$api.MsgSend(data).then(res => {
										uni.showToast({
											title: res.msg,
											icon: 'none'
										})
										if(res.code == 0){
											this.sendMsg(msg,'img');
										}
									});	
								}
							});
						}
					}
				});
			},
			// 发送消息
			sendMsg(content,type){
				//实际应用中，此处应该提交长连接，模板仅做本地处理。
				var nowDate = new Date();
				let lastid = this.msgList[this.msgList.length-1].id;
				lastid++;
				let msg = {
					id:lastid,
					uid:0,
					username:"大黑哥",
					face:'https://img.zcool.cn/community/01a3865ab91314a8012062e3c38ff6.png',
					time:nowDate.getHours()+":"+nowDate.getMinutes(),
					type:type,
					msg:content};
				this.screenMsg(msg);
			},
			
			// 处理文字消息
			addTextMsg(msg){
				this.msgList.push(msg);
			},
			// 处理语音消息
			addVoiceMsg(msg){
				this.msgList.push(msg);
			},
			// 处理图片消息
			addImgMsg(msg){
				msg = this.setPicSize(msg);
				this.msgImgList.push(msg.msg.url);
				this.msgList.push(msg);
			},
			// 预览图片
			showPic(row){
				
				uni.previewImage({
					indicator:"none",
					current:row.msg.url,
					urls: this.msgImgList
				});
			}
		}
	}
</script>

<style lang="scss">
page{
	background-color: #e9e9e9;
}
::-webkit-scrollbar{
width: 0;
height: 0;
color: transparent;
}
.hidden{
	display: none !important;
}
.input-box{
	&.hideEmoji{animation: hideEM .15s linear both;}
	&.showEmoji{animation: showEM .15s linear both;}
	width: 100%;
	min-height: 100upx;
	padding: 0 1%;
	background-color: #f2f2f2;
	display: flex;
	position: fixed;
	z-index: 20;
	bottom: 0;
	.voice,.more{
		flex-shrink: 0;
		width: 90upx;
		height: 100upx;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.send{
		//H5发送按钮左边距
		/* #ifdef H5 */
		margin-left: 20upx;
		/* #endif */
		flex-shrink: 0;
		width: 100upx;
		height: 100upx;
		display: flex;
		align-items: center;
		.btn{
			width: 90upx;
			height: 56upx;
			display: flex;
			justify-content: center;
			align-items: center;
			background:linear-gradient(to right,#f09b37,#eb632c);
			color: #fff;
			border-radius: 6upx;
			font-size: 24upx;
		}
	}
	.textbox{
		width: 100%;
		min-height: 70upx;
		margin-top: 15upx;
		.voice-mode{
			width: calc(100% - 2upx);
			height: 68upx;
			border-radius: 70upx;
			border:solid 1upx #cdcdcd;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 28upx;
			background-color: #fff;
			color: #555;
			&.recording{
				background-color: #e5e5e5;
			}
		}
		.text-mode{
			width: 100%;
			min-height: 70upx;
			display: flex;
			background-color: #fff;
			border-radius: 40upx;
			.box{
				width: 100%;
				padding-left: 30upx;
				min-height: 70upx;
				display: flex;
				align-items: center;
				textarea{
					width: 100%;
				}
			}
			.em{
				flex-shrink: 0;
				width: 80upx;
				height: 70upx;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
	}
}
.content{
	width: 100%;
	.msg-list{
		width: 100%;
		position: absolute;
		padding: 0 2%;
		top: 0;
		bottom: 100upx;
		.row{
			&:first-child{
				margin-top: 20upx;
			}
			padding: 20upx 0;
			.my .left,.other .right{
				width: 100%;
				display: flex;
				.bubble{
					max-width: 70%;
					min-height: 50upx;
					border-radius: 10upx;
					padding: 15upx 20upx;
					font-size: 32upx;
					// display: flex;
					// align-items: center;
					// font-size: 32upx;
					// word-break: break-word;
					&.img{
						background-color: transparent;
						padding:0;
						overflow: hidden;
						image{
							max-width: 350upx;
							max-height: 350upx;
						}
					}
					&.voice{
						.iconfont{
							font-size: 40upx;
							display: flex;
							align-items: center;
						}
						.iconfont:after
						{
							content:" ";
							width: 53upx;
							height: 53upx;
							border-radius: 100%;
							position: absolute;
							box-sizing: border-box;
						}
						.length{
							font-size: 28upx;
						}
					}
				}
			}
			.my .right,.other .left{
				flex-shrink: 0;
				width: 80upx;
				height: 80upx;
				image{
					width: 80upx;
					height: 80upx;
					border-radius: 10upx;
				}
			}
			.my{
				width: 100%;
				display: flex;
				justify-content: flex-end;
				.left{
					min-height: 80upx;
					
					align-items: center;
					justify-content: flex-end;
					.bubble{
						background-color: #f06c7a;
						color: #fff;
						&.voice{
							.iconfont{
								color: #fff;
							}
							.length{
								margin-right: 20upx;
							}
						}
						&.play{
							@keyframes my-play {
								0% {
									transform: translateX(80%);
								}
								100% {
									transform: translateX(0%);
								}
							}
							.iconfont:after
							{
								border-left: solid 10upx rgba(240,108,122,.5);
								animation: my-play 1s linear infinite;
							}
						}
					}
				}
				.right{
					margin-left: 15upx;
				}
			}
			.other{
				width: 100%;
				display: flex;
				.left{
					margin-right: 15upx;
				}
				.right{
					flex-wrap: wrap;
					.username{
						width: 100%;
						height: 45upx;
						font-size: 24upx;
						color: #999;
						display: flex;
						.name{
							margin-right: 50upx;
						}
					}
					.bubble{
						background-color: #fff;
						color: #333;
						&.voice{
							.iconfont{
								color: #333;
								
							}
							.length{
								margin-left: 20upx;
							}
						}
						&.play{
							@keyframes other-play {
								0% {
									transform: translateX(-80%);
								}
								100% {
									transform: translateX(0%);
								}
							}
							.iconfont:after
							{
								border-right: solid 10upx rgba(255,255,255,.8);
								
								animation: other-play 1s linear infinite;
							}
						}
					}
				}
			}
		}
	}
}
</style>
